﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Heritage.Codebox;
using Heritage.Models;

namespace Heritage.Controllers
{
    public class SocialController : Controller
    {

        [AuthorizedValidated]
        [GameMaster]
        public ActionResult WriteMessage()
        {
            return View();
        }

        [AcceptVerbs(HttpVerbs.Post)]
        [AuthorizedValidated]
        [GameMaster]
        public ActionResult WriteMessage(FormCollection coll)
        {
            try
            {
                string type = coll["adressee"];
                Guid g = Guid.Empty;
                int t = Constants.SOCIALMESSAGE_TYPE_PRIVATE;
                if (type.Equals(Constants.SOCIALMESSAGE_TYPE_NEWS+""))
                {
                    g = Constants.ADRESAT_EVERYBODY;
                    t = Constants.SOCIALMESSAGE_TYPE_NEWS;
                }
                else
                {
                    g = Guid.Parse(type);
                }
                Utils.SocialMessageCreate(g, t, coll["subject"], coll["message"]);
            }
            catch (Exception ex)
            {
                
            }
            return new RedirectResult("/Social/Mail");
        }

        [AuthorizedValidated]
        public ActionResult ReplyMail(string id, string page)
        {
            Guid g = Guid.Empty;
            Guid.TryParse(id, out g);
            HeritageEntities ents = new HeritageEntities();
            SocialMessages msg = ents.SocialMessages.Where(r => r.MsgID == g).FirstOrDefault();
            if (msg == null) return new RedirectResult("/Social/Mail/"+page);
            ViewData.Model = msg;
            ViewData["Page"] = page;
            return View();
        }

        [AcceptVerbs(HttpVerbs.Post)]
        [AuthorizedValidated]
        public ActionResult ReplyMail(FormCollection coll)
        {
            try
            {
                Guid adressee = Guid.Parse(coll["adressee"]);
                string subject = HttpUtility.HtmlDecode(coll["subject"]);
                if (!subject.StartsWith("Re: ")) subject = "Re: " + subject;
                string text = coll["message"];

                Utils.SocialMessageCreate(adressee, Constants.SOCIALMESSAGE_TYPE_PRIVATE, subject, text);
            }
            catch (Exception ex)
            {
                
            }
            string page = coll["page"];
            return new RedirectResult("/Social/Mail/" + page);
        }

        [AuthorizedValidated]
        public ActionResult Mail(string id)
        {
            int page = 1;
            int.TryParse(id, out page);
            SocialMessagePack list = Utils.GetSocialMail(page);
            List<SocialMessageModel> model = new List<SocialMessageModel>();
            foreach (var socialMessage in list.MessagesPage)
            {
                SocialMessageModel m = new SocialMessageModel();
                m.FromGuid = socialMessage.MsgFrom;
                try
                {
                    m.FromName = Utils.GetUserByID(socialMessage.MsgFrom.ToString("N")).Username;
                }
                catch
                {
                    if (m.FromGuid == Constants.ADRESAT_ROBOT)
                    {
                        m.FromName = "Система";
                    }
                    else
                    {
                        m.FromName = "Неизвестно";                        
                    }
                    m.FromGuid = Guid.Empty;
                }
                m.MessageBody = socialMessage.MsgText.Replace("\n", "<br>");
                m.MessageSubject = socialMessage.MsgSubject;
                m.MessageDate = socialMessage.MsgDate;
                m.MessageType = socialMessage.MsgType;
                m.MessageID = socialMessage.MsgID;
                m.IsRead = Utils.IsRead(socialMessage.MsgID);
                model.Add(m);
            }
            ViewData["Page"] = page;
            ViewData["AllPages"] = list.AllPages;
            ViewData.Model = model;
            return View();
        }
        [AuthorizedValidated]
        public ActionResult MarkAsRead()
        {
            string id = Request["id"];
            Guid g = Guid.Parse(id);
            Guid u = Utils.GetCurrentUser().ID;
            HeritageEntities ents = new HeritageEntities();
            SocialMessagesStatus sms =
                ents.SocialMessagesStatus.Where(r => r.UserID == u && r.MsgID == g).FirstOrDefault();
            if (sms == null)
            {
                sms = SocialMessagesStatus.CreateSocialMessagesStatus(u, g, Constants.SOCIALMESSAGE_STATUS_READ, 1);
                ents.SocialMessagesStatus.AddObject(sms);
                ents.SaveChanges();
            }
            else if (sms.Status == Constants.SOCIALMESSAGE_STATUS_UNREAD)
            {
                sms.Status = Constants.SOCIALMESSAGE_STATUS_READ;
                ents.SaveChanges();
            }
            return new EmptyResult();
        }
        [AuthorizedValidated]
        public ActionResult DeleteMessage(string id, string id2)
        {
            Guid g = Guid.Parse(id2);
            Guid u = Utils.GetCurrentUser().ID;
            HeritageEntities ents = new HeritageEntities();
            SocialMessagesStatus sms =
                ents.SocialMessagesStatus.Where(r => r.UserID == u && r.MsgID == g).FirstOrDefault();
            if (sms == null)
            {
                sms = SocialMessagesStatus.CreateSocialMessagesStatus(u, g, Constants.SOCIALMESSAGE_STATUS_DELETED, 1);
                ents.SocialMessagesStatus.AddObject(sms);
                ents.SaveChanges();
            }
            else 
            {
                sms.Status = Constants.SOCIALMESSAGE_STATUS_DELETED;
                ents.SaveChanges();
            }
            return new RedirectResult("/Social/Mail/"+id);
        }
    }
}
